﻿using System;
using System.Diagnostics;
using System.IO.IsolatedStorage;
using System.IO;

namespace WindowsPhoneAudioStreaming.Audio.Streaming
{
    public class DataUsage
    {
        private const double BytesInMegaByte = 1024 * 1024;

        public DateTime UsageStartDate { get; private set; }
        public long CellularBytes { get; private set; }

        public double CellularDataInMegaBytes
        {
            get { return CellularBytes / BytesInMegaByte; }
        }

        public long WirelessBytes { get; private set; }

        public double WirelessDataInMegaBytes
        {
            get { return WirelessBytes / BytesInMegaByte; }
        }
        public long EthernetBytes { get; private set; }

        public double EthernetDataInMegaBytes
        {
            get { return EthernetBytes / BytesInMegaByte; }
        }

        DateTime TodaysDownloadLog { get; set; }
        public long TodaysCellularBytes { get; set; }
        public long TodaysWirelessBytes { get; set; }
        public long TodaysEthernetBytes { get; set; }

        public double TodaysCellularInMegaBytes { get { return TodaysCellularBytes / BytesInMegaByte; } }
        public double TodaysWirelessInMegaBytes { get { return TodaysWirelessBytes / BytesInMegaByte; } }
        public double TodaysEthernetInMegaBytes { get { return TodaysEthernetBytes / BytesInMegaByte; } }

        public double AvgDailyCellularUsage { get {
            int days = (int)DateTime.Now.Subtract(UsageStartDate).TotalDays + 1;
            return CellularBytes / days / BytesInMegaByte;
            }
        }

        public double AvgDailyWirelessUsage { get {
            int days = (int)DateTime.Now.Subtract(UsageStartDate).TotalDays + 1;
            return WirelessBytes / days / BytesInMegaByte;
            }         
        }

        public double AvgDailyEthernet { get {
            int days = (int)DateTime.Now.Subtract(UsageStartDate).TotalDays + 1;
            return EthernetBytes / days / BytesInMegaByte;
            }
        }

        public string ConnectionType { get; set; }

        public void RefreshDataUsage()
        {
            string status = string.Empty;
            DownloadTracker.TrackerMutex.WaitOne();
            try
            {
                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (store.FileExists(DownloadTracker.LogFileName))
                    {
                        using (var istream = new IsolatedStorageFileStream(DownloadTracker.LogFileName, FileMode.Open, FileAccess.Read, store))

                        using (var sw = new StreamReader(istream))
                        {
                            status = sw.ReadToEnd();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                DownloadTracker.TrackerMutex.ReleaseMutex();
            }

            if (status != string.Empty)
            {
                string[] values = status.Split('%');
                if (values.Length == 9)
                {
                    UsageStartDate = ToDateTime(values[0]);
                    TodaysDownloadLog = ToDateTime(values[1]);
                    CellularBytes = ToBytes(values[2]);
                    WirelessBytes = ToBytes(values[3]);
                    EthernetBytes = ToBytes(values[4]);

                    TodaysCellularBytes = ToBytes(values[5]);
                    TodaysWirelessBytes = ToBytes(values[6]);
                    TodaysEthernetBytes = ToBytes(values[7]);

                    ConnectionType = values[8];
                }
            }
        }

        private DateTime ToDateTime(string value)
        {
            try
            {
                return DateTime.Parse(value, System.Globalization.CultureInfo.InvariantCulture);
            }
            catch
            {
                return DateTime.MinValue;
            }
        }

        private long ToBytes(string value)
        {
            try
            {
                return long.Parse(value, System.Globalization.CultureInfo.InvariantCulture);
            }
            catch
            {
                return 0;
            }
        }

        // this needs to me moded, indicate to audio agent that it's to reset log rather than trying to delete from client
        public void ClearDataUsageLog()
        {
            DownloadTracker.TrackerMutex.WaitOne();
            try
            {
                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (store.FileExists(DownloadTracker.LogFileName))
                    {
                        store.DeleteFile(DownloadTracker.LogFileName);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                DownloadTracker.TrackerMutex.ReleaseMutex();
            }

        }
    }
}
